package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import one.stand.code.RedisCode;
import one.stand.config.GlobalConfig;
import one.stand.config.WxConfig;
import one.stand.config.WxUrlConfig;
import one.stand.entity.ImageEntity;
import one.stand.entity.OrderNoEntity;
import one.stand.entity.TokenEntity;
import one.stand.entity.WxNoticeEntity;
import one.stand.enums.AuditStateEnums;
import one.stand.enums.LoginEnum;
import one.stand.enums.StateEnum;
import one.stand.enums.WxNoticeEnums;
import one.stand.exception.GoPayException;
import one.stand.model.*;
import one.stand.request.*;
import one.stand.response.*;
import one.stand.service.*;
import one.stand.service.impl.checkparam.CommpanyServiceCheckParam;
import one.stand.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Service
public class CompanyServiceImpl extends PublicBaseService implements CompanyService {

    @Autowired
    GlobalConfig globalConfig;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> addCompany(CompanyRequest request) {
        log.info("添加公司：{}", JSON.toJSONString(request));
        if (CommpanyServiceCheckParam.add(request)) {
            return ResultModel.checkParamFail();
        }
        if(StringUtils.isBlank(request.getPassword())){
            return ResultModel.fail("请输入企业密令~!");
        }
        CompanyModel agentModel = companyMapper.select(new CompanyModel(){{
            setCompanyKey(request.getCompanyKey());
            setIsDel(0);
        }});
        if(null==agentModel||agentModel.getIsAgent()==0){
            return ResultModel.fail("禁止创建企业");
        }
        CompanyModel companyModel = companyMapper.select(new CompanyModel(){{
            setUserId(request.getId());
            setIsDel(0);
        }});
        if(companyModel != null){
            if(companyModel.getAuditState().equals(AuditStateEnums.APPLY_IN.getCode())){
                return ResultModel.fail("您有待审核公司");
            }
            if(companyModel.getAuditState().equals(AuditStateEnums.APPLY_FAIL.getCode())){
                return ResultModel.fail("您有公司审核失败，请联系管理员");
            }
            return ResultModel.fail("已有公司，无法创建公司！");
        }
        //// 判断是否有名片 多企业不验证是否有名片
        //BusinessCardModel model = businessCardMapper.selectMyCard(new BusinessCardModel(){{
        //    setUserId(request.getId().intValue());
        //    setIsDel(0);
        //    setState(1);
        //}});
        //if(model != null){
        //    return ResultModel.fail("已有名片，无法创建公司");
        //}
        if(request.getAgentCompanyId() != null && request.getAgentCompanyId() > 0){
            Integer agentCompanyId = companyMapper.getAgentCompanyId(request.getAgentCompanyId());
            if(agentCompanyId == null || agentCompanyId <= 0){
                return ResultModel.fail("无效的代理商ID~！");
            }
        }
        CompanyModel inModel = new CompanyModel();
        BeanUtils.copyProperties(request, inModel);
        inModel.setCreateTime(currentDate());
        inModel.setUserId(request.getId());
        // 默认审核通过
        inModel.setAuditState(AuditStateEnums.APPLY_SUCCESS.getCode());
        inModel.setCompanyKey(RandomUtil.generateString(10));
        inModel.setAgentCompanyId(request.getAgentCompanyId());
        if (companyMapper.insertSelective(inModel) > 0) {
            // 添加公司成功后把公司ID保存到用户表中
            userMapper.updateByPrimaryKeySelective(new UserModel(){{
                setRoleId(inModel.getCompanyId());
                setUserId(request.getId());
            }});
            // 创建公司购买名片服务记录： 3天有效期，1张名片
            CompanyServiceModel companyServiceModel = new CompanyServiceModel();
            companyServiceModel.setCompanyId(inModel.getCompanyId());
            companyServiceModel.setPurchaseNum(2);
            companyServiceModel.setPurchaseType(2);
            companyServiceModel.setType(1);
            companyServiceModel.setHistoryNum(0);
            companyServiceModel.setAvailableNum(2);
            companyServiceModel.setCurrentNum(2);
            companyServiceModel.setCreateTime(currentDate());
            companyServiceModel.setEndTime(getBeforeOrAfterDate(new Date(),3));
            companyServiceModel.setServiceState(0);
            companyServiceMapper.insertSelective(companyServiceModel);
            // 添加公司官网信息
            WebsiteModel websiteModel = new WebsiteModel();
            websiteModel.setCompanyId(inModel.getCompanyId());
            websiteModel.setCreateTime(currentDate());
            websiteModel.setIsDel(0);
            websiteMapper.insertSelective(websiteModel);
            // 缓存公司信息
            TokenEntity entity = redisUtil.get(RedisCode.getUserLoginToken(request.getToken()));
            log.info("添加公司时根据token查询redis缓存登录信息：{}----{}",RedisCode.getUserLoginToken(request.getToken()),JSON.toJSONString(entity));
            if(entity != null) {
                entity.setCId(inModel.getCompanyId().longValue());
                entity.setRoleId(inModel.getCompanyId());
                redisUtil.set(RedisCode.getUserLoginToken(request.getToken()), entity, redisUtil.getExpire(RedisCode.getUserLoginToken(request.getToken()), TimeUnit.SECONDS), TimeUnit.SECONDS);
            }else {
                //如果未获取到token信息 则调用删除token
                redisUtil.batchDel(RedisCode.getUserLoginToken("*"+request.getId()));
                redisUtil.remove(RedisCode.getUserLoginToken("*"+request.getId()));
            }
        }
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<CompanyResponse> getCompanyId(CompanyRequest request){
        if(request == null){
            return ResultModel.checkParamFail();
        }
        CompanyModel model = companyMapper.select(new CompanyModel(){{
            setUserId(request.getId());
            setIsDel(0);
        }});
        if(model == null){
            return ResultModel.success(null);
        }
        CompanyResponse response = new CompanyResponse();
        BeanUtils.copyProperties(model,response);
        return ResultModel.success(response);

    }

    @Override
    public ResultModel<Boolean> updCompany(CompanyRequest request) {
        log.info("修改公司：{}", JSON.toJSONString(request));
        if (CommpanyServiceCheckParam.upd(request)) {
            return ResultModel.checkParamFail();
        }
        if(request.getRoleId() <= 0){
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        CompanyModel outModel = companyMapper.selectByPrimaryKey(request.getCId().intValue());
        if (null == outModel) {
            return ResultModel.fail("公司信息无效~！");
        }
        if(request.getAgentCompanyId() != null && request.getAgentCompanyId() > 0){
            Integer agentCompanyId = companyMapper.getAgentCompanyId(request.getAgentCompanyId());
            if(agentCompanyId == null || agentCompanyId <= 0){
                return ResultModel.fail("无效的代理商ID~！");
            }
        }
        BeanUtils.copyProperties(request, outModel);
        outModel.setCompanyId(request.getCId().intValue());
        companyMapper.updateByPrimaryKeySelective(outModel);
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<CompanyResponse> invitation(CompanyRequest request) {
        if (null == request.getCompanyId()) {
            return ResultModel.checkParamFail();
        }
        CompanyResponse response = companyMapper.crmCompany(request.getCompanyId().intValue());
        return ResultModel.success(response);
    }

    @Override
    public ResultModel<CompanyResponse> getCompany(CompanyRequest request) {
        CompanyModel model = new CompanyModel();
        if(request.getCompanyId() != null){
            model.setCompanyId(request.getCompanyId());
        }else{
            model.setCompanyId(request.getCId().intValue());
        }
        if(request.getMyCardId() != null){
            model.setCardId(request.getMyCardId().intValue());
        }
        CompanyResponse response = companyMapper.crmCompanyInfo(model);
        if(response != null && request.getMyCardId() != null){
            response.setCardId(request.getMyCardId().intValue());
        }
        return ResultModel.success(response);
    }

    @Override
    public ResultModel getCompanyAllInfo(CompanyRequest request) {
        log.info("下拉查询公司参数：{}",JSON.toJSONString(request));
        if(request == null){
            return ResultModel.checkParamFail();
        }
        CompanyModel companyModel = new CompanyModel();
        companyModel.setCompanyName(request.getCompanyName());
        companyModel.setIsDel(0);
        companyModel.setAuditState(1);
        companyModel.setCompanyState(1);
        List<CompanyModel> list = companyMapper.selectAll(companyModel);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<CompanyResponse> responseList = new ArrayList<>();
        list.forEach(cl -> {
            CompanyResponse companyResponse = new CompanyResponse();
            BeanUtils.copyProperties(cl, companyResponse);
            responseList.add(companyResponse);
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel<List<DynamicResponse>> selectDynamicInfo(DynamicRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        DynamicModel dynamicModel = new DynamicModel();
        BeanUtils.copyProperties(request, dynamicModel);
        dynamicModel.setCompanyId(request.getCId().intValue());
        dynamicModel.setUserId(request.getId().intValue());
        List<DynamicModel> list = dynamicMapper.select(dynamicModel);
        if (list == null) {
            return ResultModel.noData();
        }
        List<DynamicResponse> responseList = new ArrayList<>();
        list.forEach(cl -> {
            {
                DynamicResponse dynamicResponse = new DynamicResponse();
                BeanUtils.copyProperties(cl, dynamicResponse);
                dynamicResponse.setDoThumbsName(doThumbsName(cl.getDoThumbsName()));
                responseList.add(dynamicResponse);
            }
        });
        PageInfo<DynamicResponse> pageInfo = new PageInfo<>(responseList);
        return ResultModel.success(pageInfo.getList());
    }

    @Override
    public ResultModel<List<DynamicResponse>> getDynamicInfo(DynamicRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        return selectDynamicInfo(request);
    }

    @Override
    public ResultModel selectComment(CommentRequest request) {
        if(request == null){
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(),request.getPageSize());
        CommentModel model = new CommentModel();
        model.setDynamicId(request.getDynamicId());
        List<CommentModel> list = commentMapper.select(model);
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        List<CommentResponse> responseList = new ArrayList<>();
        list.forEach(obj->{{
            CommentResponse response = new CommentResponse();
            BeanUtils.copyProperties(obj,response);
            responseList.add(response);
        }});
        PageInfo<CommentResponse> pageInfo = new PageInfo<>(responseList);
        return ResultModel.success(pageInfo.getList());
    }

    @Override
    public ResultModel addDynamicInfo(DynamicRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if(request.getRoleId() <= 0){
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        DynamicModel model = new DynamicModel();
        BeanUtils.copyProperties(request, model);
        if (model.getDynamicId() == null) {
            model.setCompanyId(request.getCId().intValue());
            model.setCreateTime(new Date());
            model.setIsDel(0);
            model.setCreateUserId(request.getId().intValue());
            r= dynamicMapper.insertSelective(model);
            if (r > 0) {
                return ResultModel.success();
            }
            return ResultModel.fail();
        }
        r= dynamicMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Autowired
    protected WxMessageService wxMessageService;

    @Override
    public ResultModel doComment(CommentRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CommentModel model = new CommentModel();
        BeanUtils.copyProperties(request, model);
        model.setCreateTime(new Date());
        model.setIsDel(0);
        model.setUserId(request.getId().intValue());
        model.setCoverUserId(commentMapper.selectByPrimaryKey(request.getParentId()).getUserId());
        model.setCardId(request.getMyCardId());
        r= commentMapper.insertSelective(model);
        if (r > 0) {
            // 咨询回复通知微信推送提醒
            if(request.getParentId() != null) {
                WxNoticeEntity entity = commentMapper.getSendTemplateInfo(model.getCommentId());
                String[] fillData = {entity.getNickeName(), getDay(), entity.getText()};
                wxMessageService.sendTemplate(entity.getUserOpenId(), entity.getUserFormId(), WxNoticeEnums.COMMENT_REPLY_USER.getCode(), fillData, "&cardId="+entity.getCardId()+"&companyId="+request.getCId(), LoginEnum.USER.getAccountType(),entity.getUserCompanyId());
            }
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel delComment(CommentRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CommentModel model = new CommentModel();
        model.setCommentId(request.getCommentId());
        model.setIsDel(1);
        r= commentMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel delDynamicInfo(DynamicRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if(request.getRoleId() <= 0){
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        DynamicModel model = new DynamicModel();
        model.setIsDel(1);
        model.setDynamicId(request.getDynamicId());
        r= dynamicMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel selectWebsiteInfo(WebsiteRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        // 查询公司官网
        WebsiteModel model = websiteMapper.select(new WebsiteModel(){{
            setCompanyId(request.getCId().intValue());
        }});
        if (model == null) {
            // 添加公司官网
            model = new WebsiteModel();
            model.setCompanyId(request.getCId().intValue());
            model.setCreateTime(currentDate());
            model.setIsDel(0);
            websiteMapper.insertSelective(model);
            return ResultModel.success(model.getWebsiteId());
        }
        WebsiteResponse websiteResponse = new WebsiteResponse();
        BeanUtils.copyProperties(model, websiteResponse);
        // 查询公司视频
        websiteResponse.setCompanyVideoModelList(companyVideoMapper.select(new CompanyVideoModel(){{setCompanyId(request.getCId().intValue());}}));
        return ResultModel.success(websiteResponse);
    }

    @Override
    public ResultModel selectDemand(DemandRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        DemandModel model = new DemandModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId().intValue());
        List<DemandModel> list = demandMapper.select(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<DemandResponse> responseList = new ArrayList<>();
        list.forEach(cl -> {
            DemandResponse response = new DemandResponse();
            BeanUtils.copyProperties(cl, response);
            responseList.add(response);
        });
        PageInfo<DemandResponse> pageInfo = new PageInfo<>(responseList);
        return ResultModel.success(pageInfo.getList());
    }

    @Override
    public ResultModel addWebsiteInfo(WebsiteRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if(request.getRoleId() <= 0){
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        WebsiteModel model = new WebsiteModel();
        BeanUtils.copyProperties(request, model);
        if (model.getWebsiteId() == null) {
            model.setCreateTime(currentDate());
            model.setIsDel(0);
            model.setCompanyId(request.getCId().intValue());
            r = websiteMapper.insertSelective(model);
            if (r > 0) {
                return ResultModel.success(model.getWebsiteId());
            }
            return ResultModel.fail();
        }
        model.setUpdateTime(currentDate());
        websiteMapper.updateByPrimaryKeySelective(model);
        return ResultModel.success(model.getWebsiteId());
    }

    @Override
    public ResultModel<Boolean> insertCompanyVideo(CompanyVideoRequest request) {
        if(request == null){
            return ResultModel.checkParamFail();
        }
        if(StringUtils.isBlank(request.getUrl())){
            return ResultModel.fail("请输入公司视频路径~！");
        }
        CompanyVideoModel model = new CompanyVideoModel();
        model.setUrl(request.getUrl());
        model.setCover(request.getCover());
        model.setDescribes(request.getDescribes());
        if(request.getVideoId() == null) {
            // 新增官网视频
            model.setCompanyId(request.getCId().intValue());
            model.setCreateTime(currentDate());
            model.setIsDel(0);
            model.setSort(companyVideoMapper.getMaxVideoSort(request.getCId().intValue()) + 1);
            companyVideoMapper.insertSelective(model);
        }else{
            //  修改官网视频
            model.setVideoId(request.getVideoId());
            companyVideoMapper.updateByPrimaryKeySelective(model);
        }
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Boolean> moveCompanyVideo(CompanyVideoRequest request) {
        log.info("公司视频移动移动：{}", JSON.toJSONString(request));
        if(request == null || request.getVideoId() == null || request.getType() == null){
            return ResultModel.checkParamFail();
        }
        CompanyVideoModel model = new CompanyVideoModel();
        model.setVideoId(request.getVideoId());
        model.setType(request.getType());
        model.setCompanyId(request.getCId().intValue());
        // 查询被移动的视频信息
        CompanyVideoModel companyVideoModel = companyVideoMapper.getThanVideoInfo(model);
        if(companyVideoModel == null){
            if(ONE.equals(request.getType())){
                return ResultModel.fail("到顶了，无法上移！");
            }else if(TWO.equals(request.getType())){
                return ResultModel.fail("到底了，无法下移！");
            }
        }
        // 修改公司视频排序
        model.setSort(companyVideoModel.getSort());
        if(companyVideoMapper.updateByPrimaryKeySelective(model) > 0){
            model = new CompanyVideoModel();
            model.setVideoId(companyVideoModel.getVideoId());
            model.setSort(companyVideoModel.getLastSort());
            companyVideoMapper.updateByPrimaryKeySelective(model);
            return ResultModel.success(true);
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<Boolean> delCompanyVideo(CompanyVideoRequest request) {
        if(request == null || request.getVideoId() == null){
            return ResultModel.checkParamFail();
        }
        companyVideoMapper.updateByPrimaryKeySelective(new CompanyVideoModel(){{
            setVideoId(request.getVideoId());
            setIsDel(1);
        }});
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<List<CompanyRecruitResponse>> selectCompanyRecruit(CompanyRecruitRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        CompanyRecruitModel model = new CompanyRecruitModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId().intValue());
        List<CompanyRecruitModel> list = companyRecruitMapper.select(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<CompanyRecruitResponse> responseList = new ArrayList<>();
        list.forEach(cl -> {
            CompanyRecruitResponse response = new CompanyRecruitResponse();
            BeanUtils.copyProperties(cl, response);
            responseList.add(response);
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel addCompanyRecruit(CompanyRecruitRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if(request.getRoleId() <= 0){
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        CompanyRecruitModel model = new CompanyRecruitModel();
        BeanUtils.copyProperties(request, model);
        if(request.getRecruitId() == null || request.getRecruitId() <= 0) {
            model.setCompanyId(request.getCId().intValue());
            model.setIsDel(0);
            model.setCreateTime(currentDate());
            r = companyRecruitMapper.insertSelective(model);
        }else{
            r = companyRecruitMapper.updateByPrimaryKeySelective(model);
        }
        if (r > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel addHrPhone(CompanyRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if(request.getRoleId() <= 0){
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        CompanyModel model = new CompanyModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId().intValue());
        r= companyMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel delCompanyRecruit(CompanyRecruitRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if(request.getRoleId() <= 0){
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        CompanyRecruitModel model = new CompanyRecruitModel();
        model.setRecruitId(request.getRecruitId());
        model.setIsDel(1);
        r= companyRecruitMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Autowired
    WxPayService wxPayService;

    @Autowired
    WxUrlConfig wxUrlConfig;

    @Override
    public ResultModel<String> payment(CompanyAccountRequest request) {
        if(request == null || request.getMerchantId() == null || StringUtils.isBlank(request.getKey()) || StringUtils.isBlank(request.getCertData())){
            return ResultModel.checkParamFail();
        }
        try {
            CompanyAccountModel payA = companyAccountMapper.selectPayInfo(new CompanyAccountModel() {{
                setCompanyId(request.getCId().intValue());
                setAccountType(LoginEnum.WX_PAY.getAccountType());
            }});
            if(null!=payA){
                return ResultModel.fail("您已成功绑定支付账号！");
            }


            CompanyAccountModel companyAccountModel = companyAccountMapper.selectPayInfo(new CompanyAccountModel() {{
                setCompanyId(request.getCId().intValue());
                setAccountType(LoginEnum.USER.getAccountType());
            }});
            if (null == companyAccountModel) {
              return ResultModel.fail("请先绑定小程序");
            }




            WxConfig wxConfig=new WxConfig();
            wxConfig.setAppId(companyAccountModel.getAppId());
            wxConfig.setKey(request.getKey());
            wxConfig.setMchId(request.getMerchantId());
            wxConfig.setCertData(Base64.getDecoder().decode(request.getCertData()));
            wxConfig.setHttpConnectTimeoutMs(5000);
            wxConfig.setHttpReadTimeoutMs(5000);
            WXPay wxpay = new WXPay(wxConfig);
            String no = getPayNo();
            Map<String, String> data = new HashMap<>(12);
            data.put("appid", wxConfig.getAppID());
            data.put("mch_id", request.getMerchantId());
            data.put("nonce_str", no);
            data.put("body", "crmPc支付");
            data.put("out_trade_no", no);
            data.put("fee_type", "CNY");
            data.put("total_fee", "1");
            data.put("spbill_create_ip", request.getIp());
            data.put("notify_url", wxUrlConfig.getCrmPcBackUrl());
            data.put("trade_type", "MWEB");
            JSONObject sceneInfo = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type","WAP");
            jsonObject.put("wap_url",wxUrlConfig.getWapUrl());
            jsonObject.put("wap_name","支付信息");
            sceneInfo.put("h5_info",jsonObject);
            data.put("scene_info", sceneInfo.toJSONString());
            data.put("sign", WXPayUtil.generateSignature(data, request.getKey()));
            Map<String, String> resp = wxpay.unifiedOrder(data);
            log.info("微信支付返回：" + JSON.toJSONString(resp));
            if ("SUCCESS".equals(resp.get("return_code"))) {
                // redis 保存信息
                OrderNoEntity entity = new OrderNoEntity();
                entity.setKey(request.getKey());
                entity.setCertData(request.getCertData());
                entity.setMerchantId(request.getMerchantId());
                entity.setAccountId(companyAccountModel.getAccountId());
                redisUtil.set(RedisCode.getWxKey(no),entity);
                resp.get("mweb_url");
                return ResultModel.success(resp.get("mweb_url"));
            }
            throw new Exception(resp.get("return_msg"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultModel.fail();
    }

    @Override
    public String backPayMent(String request) {
        Map<String, String> notifyMap;
        try {
            notifyMap = wxPayService.payCallback(request);
            log.info("CRM-PC微信支付回调：{}", notifyMap);
            if (notifyMap != null) {
                String no = notifyMap.get("out_trade_no");
                OrderNoEntity entity = redisUtil.get(RedisCode.getWxKey(no));
                if(entity == null){
                    wxPayService.fail();
                }
                // 付款成功
                if (PublicBaseService.SUCCESS.equals(notifyMap.get("return_code"))) {
                    redisUtil.remove(RedisCode.getWxKey(no));
                    CompanyAccountModel model = new CompanyAccountModel();
                    model.setAccountId(entity.getAccountId());
                    model.setCertData(entity.getCertData());
                    model.setKey(entity.getKey());
                    model.setMerchantId(entity.getMerchantId());
                    model.setAccountType(LoginEnum.WX_PAY.getAccountType());
                    model.setState(1);
                    companyAccountMapper.insertSelective(model);
                    return wxPayService.success();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("微信回调验证错误", e);
        }
        return wxPayService.fail();
    }
    @Autowired
    UserTaskService userTaskService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> companyTransfer(CompanyRequest request) {
        if(request.getUserId()==null){
            return ResultModel.fail("移交用户不能为空");
        }

        UserModel userModel=userMapper.selectByPrimaryKey(request.getUserId().intValue());
        if(null==userModel){
            return ResultModel.fail("移交用户不存在");
        }
        if(userModel.getRoleId()!=0){
            return ResultModel.fail("该用户下存在企业");
        }
        BusinessCardModel businessCardModel=businessCardMapper.select(new BusinessCardModel(){{
            setUserId(request.getUserId().intValue());
        }});
        if(null!=businessCardModel){
            return ResultModel.fail("该用户存下存在名片");
        }
        CompanyModel companyModel=companyMapper.selectByPrimaryKey(request.getCId().intValue());
        if(null==companyModel){
            return ResultModel.fail("企业不存在，请退出重新登录");
        }

        int delCard=businessCardMapper.delBusinessCard(new BusinessCardModel(){{
            setCompanyId(companyModel.getCompanyId());
        }});
        log.info("删除企业下所有名片：删除数量{}",delCard);

        CompanyServiceModel companyServiceModel=companyServiceMapper.selectCompanyService(new CompanyServiceModel(){{
            setCompanyId(companyModel.getCompanyId());
            setType(1);
        }});
        if(null!=companyServiceModel){
            companyServiceModel.setType(0);
            companyServiceMapper.updateByPrimaryKeySelective(companyServiceModel);
            log.info("修改名片可用数量：{}",companyServiceModel.toString());

            companyServiceModel.setPurchaseNum(delCard);
            companyServiceModel.setPurchaseType(3);
            companyServiceModel.setType(1);
            companyServiceModel.setHistoryNum(companyServiceModel.getAvailableNum());
            companyServiceModel.setAvailableNum(companyServiceModel.getCurrentNum());
            companyServiceModel.setCreateTime(currentDate());
            companyServiceModel.setServiceId(null);
            companyServiceMapper.insertSelective(companyServiceModel);
            log.info("插入名片可用数量：{}",companyServiceModel.toString());
        }
        ResultModel resultModel=userTaskService.batchDelToken(companyModel.getCompanyId());
        log.info("删除企业所有缓存信息：",resultModel.toString());
        return ResultModel.success();
    }

    @Override
    public ResultModel<Map<String, Object>> selectAgentCompanyList(CompanyRequest request) {
        log.info("查询代理商企业下公司的信息参数：{}", JSON.toJSONString(request));
        if( request == null){
            return ResultModel.noData();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CompanyModel> list = companyMapper.selectAgentCompanyList(new CompanyModel(){{
            setCompanyName(request.getCompanyName());
            setAgentCompanyId(request.getCId().intValue());
        }});
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        PageInfo<CompanyModel> pageInfo = new PageInfo(list);
        Map<String, Object> map = new HashMap<>(1);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    /**
     * 查询企业信息
     *
     * @param request
     * @return
     */
    @Override
    public ResultModel<CompanyResponse> getCompanyInfo(CompanyRequest request) {
        log.info("查询企业信息参数：{}", JSON.toJSONString(request));
        if( request == null || request.getCompanyId() == null){
            return ResultModel.noData();
        }
        CompanyModel model = companyMapper.getAdminCompanyInfo(new CompanyModel(){{
            setCompanyId(request.getCompanyId());
        }});
        CompanyResponse response = new CompanyResponse();
        if(model != null) {
            BeanUtils.copyProperties(model, response);
        }
        return ResultModel.success(response);
    }
    @Autowired
    CompanyAccontService companyAccontService;
    @Autowired
    private WxSunCodeService wxSunCodeService;
    @Override
    public ResultModel<String> invitePoster(CompanyRequest request) {

        CompanyModel companyModel=companyMapper.selectByPrimaryKey(request.getCId().intValue());
        if(null==companyModel){
            return ResultModel.fail("企业不存在,可能已经解散");
        }
        BusinessCardModel businessCardModel=businessCardMapper.selectByPrimaryKey(request.getMyCardId());
        if(null==businessCardModel){
            return ResultModel.fail("您的账号信息不存在，可能已经被提出企业了");
        }

        CompanyAccountModel companyAccountModel= companyAccontService.selectByCompanyKey(new CompanyAccountRequest(){{
            setCompanyKey(request.getCompanyKey());
            setAccountType(LoginEnum.CRM.getAccountType());
        }});
        JSONObject jsonObject=new JSONObject();
        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("company_id=").append(companyModel.getCompanyId());
        jsonObject.put("scene",stringBuffer);
        jsonObject.put("page",crmJoinCompany);
        String sunCode=  wxSunCodeService.getWxCode(jsonObject,companyAccountModel.getAppId(),companyAccountModel.getAppSecret());



        ImageEntity imageEntity=new ImageEntity();
        imageEntity.setParam(cardPosterConfig.getWhiteBackgroupColor());
        List<ImageEntity> list=new ArrayList<>();
        ImageEntity i=new ImageEntity();
        i.setType(2);
        i.setParam(companyModel.getCompanyLogo());
        i.setWidth(150);
        i.setHigh(150);
        i.setXAxis(300);
        i.setYAxis(140);
        list.add(i);

        i=new ImageEntity();
        i.setType(1);
        i.setParam("您好!");
        i.setCentered(true);
        i.setColor(new Color(56,56,56));
        i.setYAxis(348+40);
        i.setSize(42);
        i.setPlain(Font.BOLD);
        list.add(i);

        i=new ImageEntity();
        i.setType(1);
        i.setParam(businessCardModel.getName()+" 诚邀您加入");
        i.setCentered(true);
        i.setColor(new Color(56,56,56));
        i.setYAxis(454+35);
        i.setSize(36);
        i.setPlain(Font.BOLD);
        list.add(i);

        i=new ImageEntity();
        i.setType(3);
        i.setColor(new Color(81,205,203));
        i.setWidth(750);
        i.setHigh(100);
        i.setXAxis(0);
        i.setYAxis(530);
        list.add(i);

        i=new ImageEntity();
        i.setType(1);
        i.setParam(companyModel.getCompanyName());
        i.setCentered(true);
        i.setColor(Color.WHITE);
        i.setYAxis(579+20);
        i.setSize(42);
        i.setPlain(Font.BOLD);
        list.add(i);

        i=new ImageEntity();
        i.setType(1);
        i.setParam("企业密令:"+companyModel.getPassword());
        i.setCentered(true);
        i.setColor(new Color(81,205,203));
        i.setYAxis(579+103);
        i.setSize(36);
        i.setPlain(Font.BOLD);
        list.add(i);

        i=new ImageEntity();
        i.setType(2);
        i.setParam(sunCode);
        i.setWidth(299);
        i.setHigh(299);
        i.setXAxis(226);
        i.setYAxis(843);
        list.add(i);

        i=new ImageEntity();
        i.setType(1);
        i.setCentered(true);
        i.setParam("打开微信扫一扫加入企业");
        i.setSize(24);
        i.setColor(new Color(168,168,168));
        i.setYAxis(1172+23);
        i.setPlain(Font.PLAIN);
        list.add(i);
        imageEntity.setImageEntityList(list);
        String url=ossUtil.uploadObjectOSS(imageGenerateUtil.image(imageEntity),"png");
        log.info("邀请码图片地址：{}",ossUtil.getOssUrl()+url);
        return ResultModel.success(url);
    }
}